package simco.framework.gui.swing.comp;

import java.awt.Color;
import java.awt.Font;
import java.util.ResourceBundle;

import javax.swing.JOptionPane;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.PlainDocument;

import simco.framework.gui.utils.Configuration;
import simco.framework.gui.utils.LocalizationUtil;

/**
* Tato trida deklaruje dialog pro nastavovani nekterych
* vlastnosti rozmistovaciho algortimu pro rozmistovani
* grafickych objektu na platne (grafu simulovanych
* komponent).
* 
* @author Matej Prokop, mythge@students.zcu.cz
*/
public class LayoutSettingsDialog extends javax.swing.JDialog 
{
	/**
	 * Tlaticko pro ulozeni nastaveni
	 */
	private javax.swing.JButton saveButton;
	
	/**
	 * Tlacitko pro nacteni defaultnich hodnot
	 */
	private javax.swing.JButton resetButton;
	
	/**
	 * Tlacitko pro zruseni
	 */
	private javax.swing.JButton cancelButton;
	
	/**
	 * Pole pro nastaveni poctu iteraci Spring layoutu 
	 */
	private javax.swing.JTextField iterationTextField;
	
	/**
	 * Pocet pokusu o rozmisteni pri nacteni scenare
	 */
	private javax.swing.JTextField loadLayoutTextField;
	
	/**
	 * Pocet pokusu o rozmisteni pri vyzadanem prerozmistovani
	 */
	private javax.swing.JTextField reLayoutTextField;
	
	// popisky:
    private javax.swing.JLabel algorithmTitleLabel;
    private javax.swing.JLabel iterationLabel;
    private javax.swing.JLabel loadLayoutLabel;
    private javax.swing.JLabel reLayoutLabel;
    private javax.swing.JLabel useTitleLabel;
    private javax.swing.JLabel descriptionLabel;

	/**
	 * Reference na objekt s nactenou lokalizaci
	 */
    private ResourceBundle locResource;
    
	/**
	 * Pismo pro vykresleni nadpisu
	 */
    private final Font titleFont = new Font("Tahoma", Font.BOLD, 11 );
    
	/**
	 * Pismo pro vykreslovani standarniho textu 
	 */
    private final Font descriptionFont = new Font("Tahoma", Font.PLAIN, 11 );
    
	/**
	 * Vytvori novy dialog pro nastaveni vlastnosti rozmistovaciho
	 * algoritmu.
	 * 
	 * @param parent reference nahlavni okno apliace
	 * @param modal log. promena jestli je diaglo modalni
	 */
    public LayoutSettingsDialog(java.awt.Frame parent, boolean modal) 
    {
        super(parent, modal);
        this.locResource = LocalizationUtil.getResource(this.getClass().getSimpleName());      
        this.setLocationRelativeTo(parent);
        
        setResizable(false);
        
        initComponents();
    }

    /**
     * Osetruje udalost zmacknuti tlaticko pro ulozeni nastaveni. 
     */
    private void saveBtnPressed()
    {
    	iterationTextField.setBackground(Color.WHITE);
    	loadLayoutTextField.setBackground(Color.WHITE);
    	reLayoutTextField.setBackground(Color.WHITE);
    	
    	if(iterationTextField.getText().isEmpty() || 
    			loadLayoutTextField.getText().isEmpty() || 
    			reLayoutTextField.getText().isEmpty() )
    	{
    		JOptionPane.showMessageDialog(this, locResource.getString("checker.fillAll"));
    		return;
    	}
    	
    	boolean allCorrect = true;
    	int iterationCount = Integer.parseInt(iterationTextField.getText());
    	if(iterationCount <= 0)
    	{
    		iterationTextField.setBackground(Color.YELLOW);
    		allCorrect = false;
    	}
    	    	
    	int loadLayoutAttempsCount = Integer.parseInt(loadLayoutTextField.getText());
    	if(loadLayoutAttempsCount <= 0)
    	{
    		loadLayoutTextField.setBackground(Color.YELLOW);
    		allCorrect = false;
    	}
    	
    	int reLayoutAttempsCount = Integer.parseInt(reLayoutTextField.getText());
    	if(reLayoutAttempsCount <= 0)
    	{
    		reLayoutTextField.setBackground(Color.YELLOW);
    		allCorrect = false;
    	}
    	
    	if(allCorrect)
    	{
    		Configuration.setLayoutIterationsCount(iterationCount);
    		Configuration.setLoadLayoutAttempsCount(loadLayoutAttempsCount);
    		Configuration.setReLayoutAttempsCount(reLayoutAttempsCount);
    		
    		this.dispose();
    	}
    	else
    	{
    		JOptionPane.showMessageDialog(this, LocalizationUtil.getGeneralResource().getString("dialogs.correctYellow"));
    	}
    	
    }
    
    /**
     * Osetruje udalost zmacknuti tlaticko pro nacteni defaultniho nastaveni. 
     */
    private void resetBtnPressed()
    {
    	iterationTextField.setText(locResource.getString("iterationTextField.text"));
    	loadLayoutTextField.setText(locResource.getString("loadLayoutTextField.text"));
    	reLayoutTextField.setText(locResource.getString("reLayoutTextField.text"));
    }

    /**
     * Osetruje udalost zmacknuti tlaticko pro zruseni. 
     */
    private void cancelBtnPressed()
    {
    	this.dispose();
    }

    /**
     * Inicializuje a rozmisti komponenty na dialogu
     */
    private void initComponents() 
    {

        algorithmTitleLabel = new javax.swing.JLabel();
        iterationLabel = new javax.swing.JLabel();
        loadLayoutLabel = new javax.swing.JLabel();
        reLayoutLabel = new javax.swing.JLabel();
        saveButton = new javax.swing.JButton(locResource.getString("saveButton.label"));
        resetButton = new javax.swing.JButton(locResource.getString("resetButton.label"));
        cancelButton = new javax.swing.JButton(locResource.getString("cancelButton.label"));
        useTitleLabel = new javax.swing.JLabel();
        descriptionLabel = new javax.swing.JLabel();
        
        iterationTextField = new javax.swing.JTextField(new Numeric(6), 
        		"" + Configuration.getLayoutIterationsCount(), 1);
        loadLayoutTextField = new javax.swing.JTextField(new Numeric(3), 
        		"" + Configuration.getLoadLayoutAttempsCount(), 1);
        reLayoutTextField = new javax.swing.JTextField(new Numeric(3),
        		"" + Configuration.getReLayoutAttempsCount(), 1);
        

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle(locResource.getString("Form.title")); // NOI18N
        setName("Form"); // NOI18N

        algorithmTitleLabel.setFont(titleFont); // NOI18N
        algorithmTitleLabel.setText(locResource.getString("algorithmTitleLabel.text")); // NOI18N
        algorithmTitleLabel.setName("algorithmTitleLabel"); // NOI18N

        iterationLabel.setText(locResource.getString("iterationLabel.text")); // NOI18N
        iterationLabel.setName("iterationLabel"); // NOI18N

        iterationTextField.setHorizontalAlignment(javax.swing.JTextField.RIGHT);
        iterationTextField.setName("iterationTextField"); // NOI18N

        loadLayoutLabel.setText(locResource.getString("loadLayoutLabel.text")); // NOI18N
        loadLayoutLabel.setName("loadLayoutLabel"); // NOI18N

        loadLayoutTextField.setHorizontalAlignment(javax.swing.JTextField.RIGHT);
        loadLayoutTextField.setName("loadLayoutTextField"); // NOI18N

        reLayoutLabel.setText(locResource.getString("reLayoutLabel.text")); // NOI18N
        reLayoutLabel.setName("reLayoutLabel"); // NOI18N

        reLayoutTextField.setHorizontalAlignment(javax.swing.JTextField.RIGHT);
        reLayoutTextField.setName("reLayoutTextField"); // NOI18N

        saveButton.setName("saveButton"); // NOI18N
        saveButton.addActionListener(new java.awt.event.ActionListener() 
        {
            public void actionPerformed(java.awt.event.ActionEvent evt) 
            {
            	saveBtnPressed();
            }
        });

        resetButton.setName("resetButton"); // NOI18N
        resetButton.addActionListener(new java.awt.event.ActionListener() 
        {
            public void actionPerformed(java.awt.event.ActionEvent evt) 
            {
            	resetBtnPressed();
            }
        });

        cancelButton.setName("cancelButton"); // NOI18N
        cancelButton.addActionListener(new java.awt.event.ActionListener() 
        {
            public void actionPerformed(java.awt.event.ActionEvent evt) 
            {
            	cancelBtnPressed();
            }
        });

        useTitleLabel.setFont(titleFont); // NOI18N
        useTitleLabel.setText(locResource.getString("useTitleLabel.text")); // NOI18N
        useTitleLabel.setName("useTitleLabel"); // NOI18N

        descriptionLabel.setFont(descriptionFont); // NOI18N
        descriptionLabel.setText(locResource.getString("descriptionLabel.text")); // NOI18N
        descriptionLabel.setName("descriptionLabel"); // NOI18N

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(iterationLabel)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 156, Short.MAX_VALUE)
                                .addComponent(iterationTextField, javax.swing.GroupLayout.PREFERRED_SIZE, 113, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addGap(15, 15, 15))
                            .addComponent(algorithmTitleLabel, javax.swing.GroupLayout.DEFAULT_SIZE, 419, Short.MAX_VALUE)
                            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                                .addComponent(saveButton)
                                .addGap(18, 18, 18)
                                .addComponent(resetButton)
                                .addGap(18, 18, 18)
                                .addComponent(cancelButton)))
                        .addGap(23, 23, 23))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(useTitleLabel, javax.swing.GroupLayout.DEFAULT_SIZE, 419, Short.MAX_VALUE)
                        .addGap(23, 23, 23))
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(reLayoutLabel)
                                    .addComponent(loadLayoutLabel))
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 77, Short.MAX_VALUE)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                                    .addComponent(reLayoutTextField)
                                    .addComponent(loadLayoutTextField, javax.swing.GroupLayout.DEFAULT_SIZE, 112, Short.MAX_VALUE)))
                            .addComponent(descriptionLabel, javax.swing.GroupLayout.Alignment.LEADING))
                        .addContainerGap(38, Short.MAX_VALUE))))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(algorithmTitleLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(iterationLabel)
                    .addComponent(iterationTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(29, 29, 29)
                .addComponent(useTitleLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(descriptionLabel)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 29, Short.MAX_VALUE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(loadLayoutLabel)
                    .addComponent(loadLayoutTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(reLayoutLabel)
                    .addComponent(reLayoutTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(26, 26, 26)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(cancelButton)
                    .addComponent(resetButton)
                    .addComponent(saveButton))
                .addContainerGap())
        );

        pack();
    }
    
    /**
     * Implementace dokumentu zajistujici kontrolu jeho obsahu, tak
     * aby obsahem bylo pouze cislo urcite delky (poctu
     * znaku - cislic)
     * 
     * @author Matej Prokop, mythge@students.zcu.cz
     */
    class Numeric extends PlainDocument 
    {	
 	   /**
 	    * Maximalni delka obsahu
 	    */    	
    	private final int MAX_LENGTH;
 
	   	/**
	   	 * Vytovri novy objekt kontrolujici delku obsahu
	   	 * @param maxLength maximalni povolena delka obsahu
	   	 */
    	public Numeric(int maxLength)
    	{
    		MAX_LENGTH = maxLength;
    	}
    	
    	public void insertString(int offs, String str, AttributeSet a) throws BadLocationException 
    	{
    		if (str == null) 
    		{
    			return;
    		}
    
    		// neni prekrocena maximalni delka?
    		if (MAX_LENGTH - getLength() <= 0) 
    		{
    		    return;
    		}
    		    		
    		char[] chars = str.toCharArray();
    		for(char c : chars)
    		{
    			// testuje jsouli vepsane znaky pouze cislice
    			if(!Character.isDigit(c))
    			{
    				return;
    			}
    		}

    		// prida do pole obsahu retezce str
    		super.insertString(offs, new String(chars), a);
    	}
    }

}
